package file

import (
	"context"
	"fmt"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/utils/ossfile"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/vars"
	"strings"
	"time"
)

type fileService struct {
	fileRepo FileRepositoryIface
}

// NewFileService 创建构造函数
func NewFileService(fileRepo FileRepositoryIface) FileSerivceIface {
	return &fileService{
		fileRepo: fileRepo,
	}
}

func (s *fileService) GetPolicyToken(ctx context.Context, business, tenantCode string) (ossfile.PolicyToken, error) {
	host := strings.Replace(vars.OssSetting.EndPoint, "https://", "https://"+vars.OssSetting.BucketName+".", 1)
	ossSignature := &ossfile.OssSignature{
		AccessKeyId:     vars.OssSetting.AccessKeyId,
		AccessKeySecret: vars.OssSetting.AccessKeySecret,
		Host:            host,
	}
	//"https://gfyx-saas-test.oss-cn-shenzhen.aliyuncs.com/oppty%2Fycg%2F202307%2F1894a05a4248c6d1a968bca7bf053c704431.apk?Expires=1689666187&OSSAccessKeyId=LTAI5tAkWjrrenAugNcuuWTA&Signature=zK2R1DmbY9F1RaKrN%2Fu5YHjkN7I%3D",
	uploadDir := ""
	tTime := time.Now().Format("200601")
	if tenantCode != "" {
		uploadDir = fmt.Sprintf("%s/%s/%s/", business, tenantCode, tTime)
	} else {
		uploadDir = fmt.Sprintf("%s/%s/", business, tTime)
	}
	policyToken := ossSignature.GetPolicyToken(uploadDir)

	return policyToken, nil
}

func (s *fileService) SaveToFile(ctx context.Context, ossFilePath, fileType, fileName, business string, size int64, isPrivate int64, tenantCode string) (string, error) {
	fileUid, err := s.fileRepo.SaveToFile(ctx, ossFilePath, fileType, fileName, business, size, isPrivate, tenantCode)
	if err != nil {
		return "", err
	}
	return fileUid, nil
}
